package com.example.servlet;

import com.example.dao.AnswerDAO;
import com.example.model.Answer;
import com.example.model.User;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/answer")
public class AnswerServlet extends HttpServlet {
    private AnswerDAO answerDAO;

    @Override
    public void init() throws ServletException {
        try {
            answerDAO = new AnswerDAO();
        } catch (Exception e) {
            throw new ServletException("初始化回答 DAO 失败", e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        String questionIdParam = request.getParameter("question_id");
        String content = request.getParameter("content");

        if (questionIdParam == null || questionIdParam.isEmpty() || content == null || content.trim().isEmpty()) {
            request.setAttribute("error", "回答内容不能为空");
            request.getRequestDispatcher("viewPost?id=" + request.getParameter("question_id")).forward(request, response);
            return;
        }

        int questionId;
        try {
            questionId = Integer.parseInt(questionIdParam);
        } catch (NumberFormatException e) {
            request.setAttribute("error", "无效的帖子 ID");
            request.getRequestDispatcher("viewPost?id=" + request.getParameter("question_id")).forward(request, response);
            return;
        }

        try {
            Answer newAnswer = new Answer();
            newAnswer.setQuestionId(questionId);
            newAnswer.setUserId(((User) session.getAttribute("user")).getId());
            newAnswer.setContent(content);

            answerDAO.addAnswer(newAnswer);
            response.sendRedirect("viewPost?id=" + questionId);
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("error", "数据库错误: " + e.getMessage());
            request.getRequestDispatcher("viewPost?id=" + questionId).forward(request, response);
        }
    }
}